package com.fkframe.codegener.ui.view;

import heip.generator.entity.ColumnClazz;
import heip.generator.entity.PropEditor;
import heip.generator.entity.PropEditor.EditType;
import heip.generator.entity.TableClazz;
import heip.generator.entity.ValidateRule;
import heip.generator.entity.ValidateRule.ValidateType;
import heip.generator.main.SingleTableGenerator2;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import cn.org.rapid_framework.generator.GeneratorProperties;

import com.fkframe.codegener.ui.EETSoftFrame;

/**
 * 单表树生成机制
 * 
 * @author AGUU
 * 
 */
public class TreeTableGenerView extends JPanel implements ActionListener {
	private JTextField txtModule;
	private JTextField txtTable;

	private EETSoftFrame parentFrame;

	private JButton btnLoad;
	
	private JButton btnTree;
	
	private JButton btnGener;
	private JPanel panel;
	private JPanel mainPanel;
	private JViewport jViewport;
	private JTable table;
	JScrollPane scrollPane;
	
	private SimplePropTableModel tableModel = new SimplePropTableModel();
	
	public TreeTableGenerView(EETSoftFrame parent, JPanel mainPanel,JViewport jViewport) {
		this.parentFrame = parent;
		this.mainPanel = mainPanel;
		this.jViewport = jViewport;
		setLayout(new GridLayout(0, 1, 0, 0));

		JPanel panel_2 = new JPanel();
		add(panel_2);

		JLabel lblNewLabel_1 = new JLabel("模块名");
		panel_2.add(lblNewLabel_1);

		txtModule = new JTextField();
		panel_2.add(txtModule);
		txtModule.setColumns(10);

		JLabel lblNewLabel = new JLabel("表名");
		panel_2.add(lblNewLabel);

		txtTable = new JTextField();
		panel_2.add(txtTable);
		txtTable.setColumns(10);

		JButton btnNewButton = new JButton("加载");
		panel_2.add(btnNewButton);
		btnNewButton.addActionListener(this);

		btnLoad = new JButton("生成");
		panel_2.add(btnLoad);
		btnLoad.addActionListener(this);
		
		panel = new JPanel();

		
		// 声明表格模型
		LinkedHashMap<String,String> columnMap = new LinkedHashMap<String, String>();
		columnMap.put("seq", "序号");
		columnMap.put("name","属性");
		columnMap.put("cnName", "显示名");
		
		columnMap.put("isQuery", "是否查询");
		columnMap.put("isTable", "列表显示");
		columnMap.put("isEdit", "是否编辑");
		
		columnMap.put("editType", "编辑类型");
		
		columnMap.put("validateType1", "校验类型1");
		columnMap.put("validateRule1", "校验规则1");
		columnMap.put("validateType2", "校验类型2");
		columnMap.put("validateRule2", "校验规则2");
		
		tableModel.setColumnMap(columnMap);
		
		table = new JTable(tableModel);
		table.setAutoscrolls(true);
		table.setFocusable(false);
		table.setColumnSelectionAllowed(false);
		table.setRowHeight(30);
		table.setAutoResizeMode(0);
		
		SimplePropTableModel model = (SimplePropTableModel) table.getModel();
		TableColumn sportColumn = this.table.getColumn(model.getColumnNameByKey("validateType1"));
		TableColumn sportColumn2 = this.table.getColumn(model.getColumnNameByKey("validateType2"));
		setUpSportColumn(sportColumn);
		setUpSportColumn(sportColumn2);
		
		TableColumn sportColumn3 = this.table.getColumn(model.getColumnNameByKey("editType"));
		setEditTypeColumn(sportColumn3);
		
		scrollPane = new JScrollPane();

		scrollPane.setViewportView(table);
		scrollPane.setSize(600, 400);
		add(scrollPane);
	}
	private TableClazz tableClazz ;
	
	public void setEditTypeColumn(TableColumn column){
		JComboBox comboBox = new JComboBox();
		
		comboBox.addItem("");
		for(EditType type : EditType.values()){
			comboBox.addItem(type.getName());
		}
		
		column.setCellEditor(new DefaultCellEditor(comboBox));

		// Set up tool tips for the sport cells.
		DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
		//renderer.setToolTipText("Click for combo box");
		column.setCellRenderer(renderer);
	}
	
	public void setUpSportColumn(TableColumn sportColumn) {
		
		//SimplePropTableModel model = (SimplePropTableModel) table.getModel();
		//TableColumn sportColumn = this.table.getColumn(model.getColumnNameByKey("validateType1"));
		
		JComboBox comboBox = new JComboBox();
		
		comboBox.addItem("");
		for(ValidateType type : ValidateType.values()){
			comboBox.addItem(type.getName());
		}
		
		sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

		// Set up tool tips for the sport cells.
		DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
		//renderer.setToolTipText("Click for combo box");
		sportColumn.setCellRenderer(renderer);

	}
	
	public void reloadColumnPanel2() {
		// 刷新数据代码
		// 定义Vector 类型变量tmprow，colVec，并且赋值，就象上面那样，这里不重复了
		SimplePropTableModel  model= (SimplePropTableModel) table.getModel();

		String tableName = txtTable.getText();
		tableClazz = new TableClazz(tableName);
		int columnSize = tableClazz.getColumns().size();

		List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
		for (int i = 0; i < columnSize; i++) {
			ColumnClazz col = tableClazz.getColumns().get(i);
			//忽略掉ID
			if(col.isPK())continue;
			
			
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("seq", i+1);
			map.put("name",col.getName());
			map.put("cnName", col.getCnName());
			
			map.put("isQuery", false);
			map.put("isTable", true);
			map.put("isEdit", true);
			if(col.getJavaType().equals("Long")&&(col.getColumnName().indexOf("Id")!=-1)){
				map.put("editType", EditType.DIALOG.getName());
				//map.put("editRule", "");
			}else if(col.getColumnName().equals("remark")){
				map.put("editType",EditType.TEXTAREA.getName());
			}else if(col.getJavaType().equals("Date")){
				map.put("editType",EditType.DATE.getName());
			}else{
				map.put("editType", EditType.TEXTINPUT.getName());
			}
			
			map.put("validateType1","");
			map.put("validateRule1", "");
			
			map.put("validateType2","");
			map.put("validateRule2", "");
			
			data.add(map);
		}
		model.setData(data);
		table.setModel(model);
		
		SwingUtilities.updateComponentTreeUI(table);
	}
	
	public PropEditor buildEditor(String typeStr,String param){
		PropEditor editor = null;
		
		EditType edittype= null;
		for(EditType type : EditType.values()){
			if(typeStr.equals(type.getName())){
				edittype = type;
				break;
			}
		}
		
		if(edittype==null){
			edittype = EditType.TEXTINPUT;
		}
		
		switch (edittype) {
			case SELECT:
			case DIALOG:
			case TEXTINPUT:
				editor = new PropEditor(edittype);
				break;
		default:
			break;
		}
		
		return editor;
		
	}
	
	public ValidateRule buildValidateRule(String typeStr,String ruleStr){
		
		ValidateRule rule= null;
		
		ValidateType validatetype = null;
		for(ValidateType type : ValidateType.values()){
			if(typeStr.equals(type.getName())){
				validatetype = type;
				break;
			}
		}
		if(validatetype==null)return null;
		
		switch (validatetype) {
		case REQUIRED://必输校验
			rule =  new ValidateRule(ValidateType.REQUIRED);
			return rule;
		case  LENGTH://长度校验
			rule = new ValidateRule(ValidateType.LENGTH);
			String[] sizes = ruleStr.split(",");
			if(sizes.length>1){
				rule.setMinSize(sizes[0]);
				rule.setMaxSize(sizes[1]);						
			}else{
				rule.setMaxSize(sizes[0]);
			}
			break;
		case INTEGER://整数校验
			rule = new ValidateRule(ValidateType.INTEGER);
			String[] ss = ruleStr.split(",");
			if(ss.length>1){
				rule.setMin(ss[0]);
				rule.setMax(ss[1]);						
			}else{
				rule.setMax(ss[0]);
			}
			break;
		case DECIMAL:
			String[] sss = ruleStr.split(",");
			rule = new ValidateRule(ValidateType.DECIMAL);
			if(sss.length>1){
				rule.setMin(sss[0]);
				rule.setMax(sss[1]);						
			}else{
				rule.setMax(sss[0]);
			}
			break;
		default:
			break;
		}
		
		return rule;
	}
	
	public void getTableValue(){
		List<Map<String,Object>> data = ((SimplePropTableModel)table.getModel()).getTableData();
		for(Map<String,Object> row :data){
			String columnName = (String)row.get("name");
			String columnCnName = (String) row.get("cnName");
			boolean isQuery = (Boolean)row.get("isQuery");
			boolean isTable = (Boolean)row.get("isTable");
			boolean isEdit = (Boolean)row.get("isEdit");
			
			String validateTypeName1 = (String) row.get("validateType1"); 
			String validateRule1 = (String) row.get("validateRule1");
			String validateTypeName2 = (String) row.get("validateType2"); 
			String validateRule2 = (String) row.get("validateRule2");
			//String validateTypeName3 = (String) row.get("validateType3"); 
			//String validateRule3 = (String) row.get("validateRule3");
			String editType=(String)row.get("editType");
			
			for(ColumnClazz col:this.tableClazz.getColumns()){
				if(col.getPropName().equals(columnName)){
					col.setPropCnName(columnCnName);
					col.setQueryCol(isQuery);
					col.setTableCol(isTable);
					col.setEditCol(isEdit);
					
					col.clearRule();//清空规则
					//校验规则
					ValidateRule rule = buildValidateRule(validateTypeName1, validateRule1); 
					if(rule!=null)col.addValidateRule(rule);
					ValidateRule rule2 = buildValidateRule(validateTypeName2, validateRule2); 
					if(rule2!=null)col.addValidateRule(rule2);
					
					if(editType!=null){
						PropEditor e = buildEditor(editType, null);
						col.setPropEditor(e);
					}
					
					//ValidateRule rule3 = buildValidateRule(validateTypeName3, validateRule3); 
					//if(rule3!=null)col.addValidateRule(rule3);
				}
			}
			
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("加载")){
			String moduleName = txtModule.getText();
			String tableName = txtTable.getText();
			reloadColumnPanel2();
		}else{
			getTableValue();
			doGenerAction();
		}
	}
	
	public void doGenerAction(){
		try {
			String moduleName = txtModule.getText();
			String tableName = txtTable.getText();
			
			//1 生成
			if(this.tableClazz==null){
				this.tableClazz = new TableClazz(tableName);
			}
			SingleTableGenerator2 gener = new SingleTableGenerator2(moduleName);
			gener.generatorTree(tableName, tableClazz);
			
			Runtime.getRuntime().exec("cmd.exe /c start "+ GeneratorProperties.getRequiredProperty("outRoot"));
		} catch (Exception ee) {
			return;
		}
	}
}